package Gson;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

public class GsonServer {
	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		Gson gson = new Gson(); 
	    ServerSocket s = new ServerSocket(90);
	    Socket clientSocket = s.accept();
	    System.out.println("Client was accepted");
	    JsonReader reader = new JsonReader(new InputStreamReader(clientSocket.getInputStream()));
    	JsonWriter writer = new JsonWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
	    JsonWriter writerFile = new JsonWriter(new OutputStreamWriter(new FileOutputStream(args[0])));
	    SensorData obj;
	    do {
	    	obj = gson.fromJson(reader, SensorData.class);
	        if (obj != null) {
	        	gson.toJson(obj, SensorData.class, writerFile);
	        	gson.toJson("end", String.class, writer);
	        	writer.flush();
	        	writerFile.flush();
	        }
	    } while (obj != null);
	    reader.close();
	    writer.close();
	    writerFile.close();
	    s.close();
	}
}
